﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Mail;
using System.Diagnostics;
using System.Text;

namespace CheckMemcached
{
    public static class GetConfig
    {
        public static string AppliactionName = "CheckMemcached";
        /// <summary>
        /// 得到所有Memcached服务器
        /// </summary>
        /// <returns></returns>
        public static List<Server> GetMemcachedServer()
        {
            List<Server> ListMemcached = new List<Server>();
            MemcachedServer ms = ConfigurationManager.GetSection("MemcachedServer") as MemcachedServer;
            foreach (Server mc in ms.Memcached)
            {
                ListMemcached.Add(mc);
            }
            return ListMemcached;
        }
        /// <summary>
        /// 得到邮件发送地址
        /// </summary>
        /// <returns></returns>
        public static List<MailAddress> GetMailToAddress()
        {
            MailToAddressSection mta = ConfigurationManager.GetSection("MailToAddressSection") as MailToAddressSection;
            List<MailAddress> ListMailAddress = new List<MailAddress>();
            foreach (MailAddress ma in mta.MailToAddressCollection)
            {
                ListMailAddress.Add(ma);
            }
            return ListMailAddress;
        }
        /// <summary>
        /// 返回每几分钟检查一次
        /// </summary>
        /// <returns></returns>
        public static int RepeatMinute()
        {
            string RepeatMinuteString = System.Configuration.ConfigurationManager.AppSettings["RepeatMinute"];
            int RepeatMinute = int.Parse(RepeatMinuteString);
            return RepeatMinute;
        }

        /// <summary>
        /// 是否重启服务
        /// </summary>
        /// <returns></returns>
        public static bool IsRestartServier()
        {
            string IsRestartString = System.Configuration.ConfigurationManager.AppSettings["IsResterMemcached"];
            bool IsRestart = IsRestartString.ToLower() == "true" ? true : false;
            return IsRestart;
        }

        /// <summary>
        /// 得到发邮件的间格时间
        /// </summary>
        /// <returns></returns>
        public static int SendMailRepeatMinute()
        {
            string SendMailRepeatMinuteString = System.Configuration.ConfigurationManager.AppSettings["SendMailRepeatMinute"];
            int SendMailRepeatMinute = int.Parse(SendMailRepeatMinuteString);
            return SendMailRepeatMinute;
        }

        /// <summary>
        /// 是否写入成功检查的信息,如果为false,则只写失败的信息
        /// </summary>
        /// <returns></returns>
        public static bool IsWriteSuccessEventLog()
        {
            string IsWriteSuccessEventLogString = System.Configuration.ConfigurationManager.AppSettings["WriteEventLogSuccessInfo"];
            bool IsWriteSuccessEventLog = IsWriteSuccessEventLogString.ToLower() == "true" ? true : false;
            return IsWriteSuccessEventLog;
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="memcacheds">停止服务的Memcached</param>
        public static void SendMail(List<ErrorServer> Servers)
        {
            if (Servers.Count == 0)
            {
                return;
            }
            MailMessage Message = new MailMessage();
            Message.BodyEncoding = System.Text.Encoding.Default;
            Message.IsBodyHtml = true;
            Message.Subject = "Memcached stop the service";
            foreach (MailAddress ma in GetConfig.GetMailToAddress())
            {
                Message.To.Add(ma.Address);
            }
            if (Message.To.Count == 0)
            {
                return;
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("Stop the service host:<br/>");
            foreach (ErrorServer server in Servers)
            {
                sb.AppendFormat("<span Style=\"Color:Red;\">{0}:{1} @{2}</span><br/>", server.Host, server.Port.ToString(), server.CheckTime.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            sb.Append("<br/><br/>");
            if (EventLog.SourceExists("CheckMemcached"))
            {
                sb.Append("EventLog List<br/><ul>");
                EventLog el = new EventLog("Application", ".", "CheckMemcached");
                EventLogEntryCollection elec = el.Entries;
                foreach (EventLogEntry ele in elec)
                {
                    string EventLogType = string.Empty;
                    string StyleString = string.Empty;
                    switch (ele.EntryType)
                    {
                        case EventLogEntryType.Error: 
                            EventLogType = "&nbsp;Error";
                            StyleString = " Style=\"Color:Red;\"";
                            break;
                        case EventLogEntryType.Information: EventLogType = "&nbsp;Information"; break;
                        case EventLogEntryType.SuccessAudit: EventLogType = "&nbsp;Success"; break;
                    }
                    if (ele.InstanceId == 0 && ele.TimeWritten > DateTime.Now.AddMinutes(0 - GetConfig.SendMailRepeatMinute() - GetConfig.RepeatMinute() - 1))
                    {
                        sb.AppendFormat("<li{2}>{1}<b>{0}</b></li>", EventLogType, ele.Message, StyleString);
                    }
                }
                sb.Append("</ul>");
            }
            Message.Body = sb.ToString();
            SmtpClient sc = new SmtpClient();
            sc.Send(Message);
        }
    }
}
